package com.qys.livesMall.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.common.utils.bean.BeanProUtils;
import com.qys.livesMall.finance.model.entity.shop.FinanceShopAccountDetail;
import com.qys.livesMall.framework.view.Paging;
import com.qys.livesMall.framework.view.QysPage;
import com.qys.livesMall.shop.constants.OrderStatus;
import com.qys.livesMall.shop.constants.OrderType;
import com.qys.livesMall.shop.modal.dto.shop.order.OrderReturnSearch;
import com.qys.livesMall.shop.modal.entity.ShopOrderInfo;
import com.qys.livesMall.shop.modal.entity.ShopOrderReturnApproved;
import com.qys.livesMall.shop.mapper.ShopOrderReturnApprovedMapper;
import com.qys.livesMall.shop.modal.entity.ShopOrderReturnExpress;
import com.qys.livesMall.shop.modal.entity.ShopOrderSku;
import com.qys.livesMall.shop.modal.vo.ShopOrderReturnVO;
import com.qys.livesMall.shop.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gmx
 * @since 2023-06-23
 */
@Service
public class ShopOrderReturnApprovedServiceImpl extends ServiceImpl<ShopOrderReturnApprovedMapper, ShopOrderReturnApproved> implements ShopOrderReturnApprovedService {

    @Autowired
    private ShopOrderReturnApprovedMapper approvedMapper;

    @Autowired
    private ShopOrderSkuService shopOrderSkuService;

    @Autowired
    private ShopOrderReturnProcessService processService;

    @Autowired
    private ShopOrderInfoService shopOrderInfoService;

    @Autowired
    private ShopOrderStatusManager shopOrderStatusManager;

    @Autowired
    private ShopOrderReturnExpressService expressService;

    @Override
    public ShopOrderReturnApproved getByOrderSkuId(Long orderSkUId) {
        LambdaQueryWrapper<ShopOrderReturnApproved> wq =new LambdaQueryWrapper<>();
        wq.eq(ShopOrderReturnApproved::getOrderSkuId,orderSkUId);
        wq.last("limit 1");
        return getOne(wq);
    }

    @Override
    public QysPage<ShopOrderReturnVO> search(OrderReturnSearch search) {
        Paging<ShopOrderReturnApproved> page=approvedMapper.search(new Paging<>(search));
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return QysPage.to(page);
        }
        List<Long> orderSkuIds=page.getRecords().stream().map(ShopOrderReturnApproved::getOrderSkuId).collect(Collectors.toList());
        Map<Long, ShopOrderSku> skuMap = shopOrderSkuService.listByIds(orderSkuIds).stream().collect(Collectors.toMap(ShopOrderSku::getId, v -> v));
        List<ShopOrderReturnVO> vos=new ArrayList<>();
        page.getRecords().stream().forEach(o->{
            ShopOrderReturnVO vo= BeanProUtils.copyProperties(o,ShopOrderReturnVO::new);
            vo.setApprovedId(o.getId());
            ShopOrderSku sku=skuMap.get(o.getOrderSkuId());
            if (sku!=null){
                vo.setGoodsName(sku.getName());
                vo.setNum(sku.getNum());
                vo.setAmount(sku.getMoney());
                vo.setExpressNo(sku.getExpress());
            }
            if (!Objects.equals(vo.getType(), OrderType.ReturnType.REFUND)) {
                vo.setReturnExpress(expressService.getExpress(o.getId(), 2));
            }
            if (Objects.equals(vo.getType(), OrderType.ReturnType.EXCHANGE)) {
                vo.setPlatformReturnExpress(expressService.getExpress(o.getId(), 1));
            }

            vos.add(vo);
        });
        return QysPage.to(page).setRecords(vos);
    }

    @Override
    public R autoFinish(Long id) {
        try {
            ShopOrderReturnApproved approved=getById(id);
            if (ObjectUtils.isEmpty(approved))return R.fail(MessageUtils.message("shop.order.null"));
            if (!approved.getStatus().equals(OrderStatus.ReturnStatus.USER_RECEIVED)) {
                return R.fail(MessageUtils.message("order.status.not.return"));
            }

            LocalDateTime now = LocalDateTime.now();
            approved.setStatus(OrderStatus.ReturnStatus.RETURNED);
            approved.setUpdateTime(now);
            if(!updateById(approved)) throw new QysException(MessageUtils.message("system.error.approved"));

            processService.add(approved.getId(),approved.getStatus(),approved.getType());

            //更新dd状态
            ShopOrderSku sku=shopOrderSkuService.getById(approved.getOrderSkuId());
            sku.setOrderStatus(OrderStatus.RETURNED);
            shopOrderSkuService.updateById(sku);
            ShopOrderInfo orderInfo=shopOrderInfoService.getById(sku.getOrderId());
            List<ShopOrderSku> skus=shopOrderSkuService.getStatusByOrderId(orderInfo.getId());
            orderInfo.setOrderStatus(shopOrderStatusManager.getMainOrderStatus(skus));
            orderInfo.setEndTime(System.currentTimeMillis());
            shopOrderInfoService.updateById(orderInfo);
            return R.ok();
        }catch (QysException e){
            return R.fail(e.getMessage());
        }
    }
}
